package com.pxl.bi.bizmq.init;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import static com.pxl.bi.common.BiMqConstant.*;

/**
 * 用于创建测试程序用到的交换机和队列（在程序启动前执行一次）
 */
public class BiInitMain {
    public static void main(String[] args) {
        Connection connection = null;
        Channel channel = null;

        try {
            ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.setHost("localhost");
            connection = connectionFactory.newConnection();
            channel = connection.createChannel();

            String exchangeName = BI_EXCHANGE_NAME;
            channel.exchangeDeclare(exchangeName, "direct");

            // 创建一个队列，随机分配一个队列名称
            String queueName = BI_QUEUE_NAME;
            channel.queueDeclare(queueName, true, false, false, null);
            channel.queueBind(queueName, exchangeName, BI_ROUTING_KEY);

        } catch (Exception e) {
            System.out.println("RabbitMQ 初始化失败：" + e.getMessage());
        } finally {
            try {
                if (channel != null) {
                    channel.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception ex) {
                System.out.println("关闭连接或频道时出错：" + ex.getMessage());
            }
        }
    }
}
